#include "onlineloginform.h"
#include "ui_onlineloginform.h"

OnlineLoginForm::OnlineLoginForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::OnlineLoginForm)
{
    ui->setupUi(this);
    db = QSqlDatabase::database();
    oc = Rt::oc;

    if ( db.isOpen() || db.open() )
    {
        QSqlQuery q(db);
        q.prepare("SELECT value FROM data WHERE data = 'online_username';");
        if ( q.exec() && q.first() )
        {
            ui->username_lineEdit->setText(q.value(0).toString());
        }
        q.prepare("SELECT value FROM data WHERE data = 'online_password';");
        if ( q.exec() && q.first() )
        {
            ui->password_lineEdit->setText(q.value(0).toString());
        }
    }
    ui->save_pushButton->setEnabled(false);
    ui->test_pushButton->setDefault(true);
}

OnlineLoginForm::~OnlineLoginForm()
{
    delete ui;
}

void OnlineLoginForm::login_success()
{
    disconnect(oc, 0, this, 0);
    ui->test_pushButton->setEnabled(true);
    ui->save_pushButton->setEnabled(true);
    QMessageBox::information(this, tr("Verbindung testen"), tr("Verbindung erfolgreich hergestellt"));
    ui->save_pushButton->setDefault(true);
}

void OnlineLoginForm::login_failed()
{
    disconnect(oc, 0, this, 0);
    ui->test_pushButton->setEnabled(true);
    ui->save_pushButton->setEnabled(false);
    QMessageBox::information(this, tr("Verbindung testen"), tr("Verbindung konnte nicht hergestellt werden\nBitte Benutzername und Passwort überprüfen"));
    ui->test_pushButton->setDefault(true);
}

void OnlineLoginForm::on_test_pushButton_clicked()
{
    connect(oc, SIGNAL(login_success()), this, SLOT(login_success()));
    connect(oc, SIGNAL(login_failed(QString)), this, SLOT(login_failed()));
    ui->test_pushButton->setEnabled(false);
    oc->setUsername(ui->username_lineEdit->text());
    oc->setPassword(ui->password_lineEdit->text());
    oc->reconnect();
}

void OnlineLoginForm::on_save_pushButton_clicked()
{
    if ( db.isOpen() || db.open() )
    {
        QSqlQuery q(db);
        q.prepare("INSERT OR REPLACE INTO data (data, value) VALUES ('online_username', :username)");
        q.bindValue(":username", ui->username_lineEdit->text());
        q.exec();
        q.prepare("INSERT OR REPLACE INTO data (data, value) VALUES ('online_password', :password)");
        q.bindValue(":password", ui->password_lineEdit->text());
        q.exec();
        accept();
    }
}

void OnlineLoginForm::on_cancel_pushButton_clicked()
{
    reject();
}
